using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using TmxUtil;

namespace TmxLib
{
    [Serializable]
    public class ProjectBinary
    {
        private Project _project;
        private string _outputPath;

        public ProjectBinary(Project project, string outputPath)
        {
            _project = project;
            _outputPath = outputPath;

        }

        public string FullPath
        {
            get
            {
                return
                    new DirectoryInfo(
                        Path.Combine(new FileInfo(_project.FullName).DirectoryName, _outputPath)
                        ).FullName;
            }
        }

        public string FullName
        {
            get
            {
                string bn = Path.Combine(FullPath, _project.AssemblyName);
                switch(_project.OutputType)
                {
                    case ProjectOutputType.Windows:
                    case ProjectOutputType.Console:
                        return bn + ".exe";

                    case ProjectOutputType.Library:
                        return bn + ".dll";

                    default:
                        return bn + ".dll";
                }
            }
        }

        public bool Exists
        {
            get { return File.Exists(FullName); }
        }


        public override string ToString()
        {
            return FullName;
        }
    }

    [Serializable]
    public class ProjectBinaryCollection : Collection<ProjectBinary>
    {
        public ProjectBinaryCollection()
        {
        }


        public ProjectBinaryCollection(IEnumerable<ProjectBinary> list)
        {
            foreach (ProjectBinary binary in list)
                Add(binary);
        }

        public ProjectBinaryCollection Present
        {
            get
            {
                List<ProjectBinary> copy = new List<ProjectBinary>(this);
                List<ProjectBinary> found = copy.FindAll(delegate(ProjectBinary obj) { return obj.Exists; });
                return new ProjectBinaryCollection(found);
            }
        }

        public ProjectBinary Latest
        {
            get
            {
                List<ProjectBinary> copy = new List<ProjectBinary>(Present);
                copy.Sort(
                    delegate(ProjectBinary x, ProjectBinary y)
                        {
                            return
                                new FileInfo(x.FullName).LastWriteTimeUtc.
                                    CompareTo(
                                    new FileInfo(y.FullName).LastWriteTimeUtc);
                        });

                return copy.Count == 0 ? null : copy[copy.Count - 1];
            }
        }
    }
}
